/*
 * parameters.c
 *
 *  Created on: 2022.3.2
 *      Author: huan
 */
#include "head_user.h"
#include "head_rtthread.h"

union Parame_PID_t  Parame_PID;
union Parame_Clib_t Parame_Clib;
union Parame_FLAG_t Parame_FLAG;

Parameter_HandleTypedef Par_handle;

extern rt_thread_t IMU_thread;
void Parame_Task(void* parameter)
{
    Par_handle.readData(PID_sector);
    Par_handle.readData(Clibration_sector);

    rt_thread_startup(IMU_thread);

#ifndef AC_USING_AUTOTASK
    extern rt_thread_t Flymain_thread;
    rt_thread_startup(Flymain_thread);
#else
    extern rt_thread_t CtrlS_thread;
    rt_thread_startup(CtrlS_thread);
#endif

    while(1)
    {
        if(Parame_FLAG.Pflags)
        {
            if(Parame_FLAG.PID_PSflag)
            {
                Par_handle.saveData(PID_sector);
                Parame_FLAG.PID_PSflag = 0;
            }
            if(Parame_FLAG.Clib_PSflag)
            {
                Par_handle.saveData(Clibration_sector);
                Parame_FLAG.Clib_PSflag = 0;
            }
        }
        rt_thread_mdelay(500);
    }
}

static int16_t data_read_from_flash(Flash_sector sector_num)
{
    switch(sector_num)
    {
        case PID_sector:
        {
#ifndef USE_EXTERAL_FLASH
            Flash_Handle.readData(PID_sector, 4*54, (uint8_t*)(&Parame_PID.byte[0]));
#else
            ExFlash_Handle.readData(PID_sector*1024, 4*156, (uint8_t*)(&Parame_PID.byte[0]));
#endif
        }break;
        case Clibration_sector:
        {
#ifndef USE_EXTERAL_FLASH
            Flash_Handle.readData(Clibration_sector, 4*8, (uint8_t*)(&Parame_Clib.byte[0]));
#else
            ExFlash_Handle.readData(Clibration_sector*1024, 4*8, (uint8_t*)(&Parame_Clib.byte[0]));
#endif
        }break;

        default:break;
    }
    return 0;
}
static int16_t data_save_to_flash(Flash_sector sector_num)
{
    switch(sector_num)
    {
        case PID_sector:
        {
#ifndef USE_EXTERAL_FLASH
            Flash_Handle.eraseData(PID_sector);
            Flash_Handle.saveData(PID_sector, 4*54, (uint8_t*)(&Parame_PID.byte[0]));
#else
            ExFlash_Handle.saveData(PID_sector*1024, 4*156, (uint8_t*)(&Parame_PID.byte[0]));
#endif
        }break;
        case Clibration_sector:
        {

#ifndef USE_EXTERAL_FLASH
            Flash_Handle.eraseData(Clibration_sector);
            Flash_Handle.saveData(Clibration_sector, 4*8, (uint8_t*)(&Parame_Clib.byte[0]));
#else
            ExFlash_Handle.saveData(Clibration_sector*1024, 4*8, (uint8_t*)(&Parame_Clib.byte[0]));
#endif
        }break;

        default:break;
    }
    return 0;
}

static int parame_init(void)
{
    Par_handle.readData = data_read_from_flash;
    Par_handle.saveData = data_save_to_flash;

    Parame_FLAG.Pflags = 0;

    return 0;
}

INIT_APP_EXPORT(parame_init);
